/**
 * 6. ZigZag Conversion
 * https://leetcode.com/problems/zigzag-conversion/
 */
package lc6;

public class Main {
  public static void main(String[] args) {
    String s = "AB";
    int numRows = 1;
    String result = new Solution().convert(s, numRows);
    System.out.println(result);
  }
}

class Solution {
  public String convert(String s, int numRows) {
    if (numRows == 1) {
      return s;
    }

    StringBuilder[] sbs = new StringBuilder[numRows];
    for (int i = 0; i < numRows; i++) {
      sbs[i] = new StringBuilder();
    }

    int last = -1;
    int forward = 1;
    for (int i = 0; i < s.length(); i++) {
      if (forward > 0) {
        if (last == numRows - 1) {
          forward = -1;
          sbs[--last].append(s.charAt(i));
        } else {
          sbs[++last].append(s.charAt(i));
        }
      } else {
        if (last == 0) {
          forward = 1;
          sbs[++last].append(s.charAt(i));
        } else {
          sbs[--last].append(s.charAt(i));
        }
      }
    }
    
    for (int i = 1; i < numRows; i++) {
      sbs[0].append(sbs[i]);
    }
    return sbs[0].toString();
  }
}
